package com.mc.main;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import android.util.Log;


/**
 * @author Sajox
 *
 */
public class UdpClient extends DatagramSocket implements Runnable{
	private String host;
	private int port;
	private Thread myThread;
	
	public static final String HOST = "10.0.1.3";
	public static final int PORT = 12345;
	private List<UdpEventListener> listeners = new ArrayList<UdpEventListener>();
	public static UdpClient client;


	/**
	 * @param host Host to send to
	 * @param port Port to send to
	 * @throws SocketException
	 */
	UdpClient(String host, int port) throws SocketException{
		super(PORT);
		this.host = host;
		this.port = port;
	}
	
	public void addUdpEventListener(UdpEventListener listener){
		listeners.add(listener);
	}
	
	public void removeUdpEventListener(UdpEventListener listener){
		listeners.remove(listener);
	}
	
	/**
	 * @param dataToSend, byte array with data to send to server
	 */
	public  void send(byte[] data){
		DatagramPacket packet;
		
		try {
			packet = new DatagramPacket(data, data.length, InetAddress.getByName(host), port);
			send(packet);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * @return Returns true if a new thread is created and started, false if already started.
	 */
	public boolean startListen(){
		
		Log.v("LOG", "udp");
		if(myThread == null){
			myThread = new Thread(this);
			myThread.start();
			return true;
		}		
		return false;
	}
	

	/* (non-Javadoc)
	 *  Receive the packets in its own thread 
	 */
	public void run() {
		byte[] data = new byte[65535];
		Log.v("UDP", "Listen to port: " + this.getLocalPort());
		DatagramPacket pack = new DatagramPacket(data, data.length);
	
		try {
			while(true){
				receive(pack);
				Log.v("UDP", "tog emot");
				if(pack.getLength() != 0){
					sendEvent(new UdpEvent(this, pack.getData()));
				}
			}
		} catch (IOException e) {
			Log.v("UdpClient", e.getMessage());
		}
	}
	
	/**
	 * @param e, UdpEvent to send to listeners
	 */
	private void sendEvent(UdpEvent e){
		ListIterator<UdpEventListener> iter = listeners.listIterator();
		try {
			while(iter.hasNext()){
				iter.next().UdpEventReceived(e);
			}
		}catch(Exception e2){};
	}
}
